package jsf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import jpa.entities.Course;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jsf.session.CourseFacade;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;
import java.util.zip.ZipOutputStream;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.security.auth.message.callback.PrivateKeyCallback;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jpa.entities.Topic;
import jsf.session.TopicFacade;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;

@ManagedBean(name = "courseController")
@SessionScoped
public class CourseController implements Serializable {

    private Course current;
    private DataModel items = null;
    @EJB
    private jsf.session.CourseFacade ejbFacade;
    private jsf.session.TopicFacade ejbFacadeTopic;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private TopicController topicController = new TopicController();
    private UploadedFile file;
    private String destination = "uploaded";

    public CourseController() {
    }

    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }

    public Course getSelected() {
        if (current == null) {
            current = new Course();
            selectedItemIndex = -1;
        }
        return current;
    }
    public String ConvertDate;

    public String getConvertDate() {
        return ConvertDate;
    }

    public void setConvertDate(String ConvertDate) {
        this.ConvertDate = ConvertDate;
    }

    private CourseFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
        //return "/faces/admin/course/List.xhtml";
    }

    public String prepareListToUser() {
        recreateModel();
        return "/faces/user/course/List.xhtml";
    }
//    public Date getDatenow()
//    {
//        Date now = new Date();
//        return now; 
//    }
    public String prepareView() {
        current = (Course) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View.xhtml";
    }

    public String prepareViewToUser() {
        current = (Course) getItems().getRowData();
        FacesContext context = FacesContext.getCurrentInstance();
        context.getExternalContext().getSessionMap().put("CurrentCourse", current);
        return "/faces/user/course/View.xhtml";
    }
    public String prepareViewFromProfile(String courseName)
    {
        current = getFacade().getCourseFromCourseName(courseName);
        return "/faces/user/course/View.xhtml";
    }

    public String prepareCreate() {
        current = new Course();
        selectedItemIndex = -1;
        return "Create";
    }
    public String linkDownload(String fileName)
    {
     return getSiteRoot() + "/faces/uploaded/"+fileName;   
    }
    public String getSiteRoot()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        return request.getContextPath();
    }
    public String create() {
        try {
            copyFile(file.getFileName(), file.getInputstream());
            current.setAssignmentFile(file.getFileName());
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("CourseCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public void copyFile(String fileName, InputStream in) {
        try {

            ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance()
                    .getExternalContext().getContext();
            String realPath = ctx.getRealPath("/");
            File theDir = new File(realPath + "\\" + destination);
            // if the directory does not exist, create it
            if (!theDir.exists()) {
                boolean result = theDir.mkdir();
                if (result) {
                    System.out.println("DIR created");
                }

            }
            // write the inputStream to a FileOutputStream
            OutputStream out = new FileOutputStream(new File(theDir + "\\" + fileName));

            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = in.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }

            in.close();
            out.flush();
            out.close();

            System.out.println("New file created!");
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    public String prepareEdit() {
        current = (Course) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }
    //admin

    public String update() {
        try {
            copyFile(file.getFileName(), file.getInputstream());
            current.setAssignmentFile(file.getFileName());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("CourseUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    //user

    public String updateForUser() {
        try {
            copyFile(file.getFileName(), file.getInputstream());
            current.setAssignmentFile(file.getFileName());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("CourseUpdated"));
            return "/faces/user/course/View.xhtml";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (Course) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("CourseDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }
    public HttpServletRequest request;
    private Topic topic;

    public Topic getTopic() {
        return topic;
    }

    public void setTopic(Topic topic) {
        this.topic = topic;
    }

    //admin
    public String findAllCourseByTopicId() {
        try {
            items = topic != null 
                    ? new ListDataModel(ejbFacade.findCourseByTopicId(topic))
                    : new ListDataModel(ejbFacade.showAllCourse());
            return "/faces/admin/course/List.xhtml";

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    public String showAllCourse() {
        try {
            items = new ListDataModel(ejbFacade.showAllCourse());
            return "/faces/admin/course/List.xhtml";

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    public String showAllCourseByUser() {
        try {
            items = new ListDataModel(ejbFacade.showAllCourse());
            return "/faces/user/course/List.xhtml";

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    public List<Course> showTop3CourseByUser() {
        try {
            return (ejbFacade.showTop3Course().subList(0, 3));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    //user

    public String findAllCourseByTopicIdForUser() {
        try {
            items = new ListDataModel(ejbFacade.findCourseByTopicId(topic));
            return "/faces/user/course/List.xhtml";

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Course.class)
    public static class CourseControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            CourseController controller = (CourseController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "courseController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Course) {
                Course o = (Course) object;
                return getStringKey(o.getCourseId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Course.class.getName());
            }
        }
    }
}
